<?php

namespace app\system\service;

use think\facade\Db;

class UserRoleService
{
    public function saveUserRole($request)
    {

        try {
            $userId = $request->post('userId');
            $roleIds = $request->post('roleIds');
            //清理旧数据
            Db::name('user_roles')
                ->where('userId', $userId)
                ->delete();
            foreach ($roleIds as $id) {

                $data = ['roleId' => $id, 'userId' => $userId];
                $where = [];
                $where['roleId'] = ['roleId', '=', "{$id}"];
                $where['userId'] = ['userId', '=', "{$userId}"];
                //查询是否存在
                $roleMenuList = Db::table('user_roles')->where($where)->findOrEmpty();

                if (empty($roleMenuList)) {
                    $data['createdAt'] = date("Y-m-d H:i:s");
                    //插入
                    Db::name('user_roles')->insert($data);
                } else {
                    $data['updatedAt'] = date("Y-m-d H:i:s");
                    //更新
                    Db::name('user_roles')->update($data);
                }
            }

        } catch (\Exception $e) {
            return (['success' => false, 'info' => $e->getMessage()]);
        }
        return (['success' => true, 'info' => '保存成功!']);
    }
}